<template>
  <div class="page">
    <BrandHeader />
    <div class="container">
      <div class="head">
        <button class="back-btn" @click="goBack" aria-label="返回上一页">返回</button>
        <h2 class="title">我的评分</h2>
        <div class="sub" v-if="items.length">共 {{ items.length }} 部</div>
      </div>

      <div v-if="items.length" class="grid">
        <div class="cell" v-for="m in pageItems" :key="m.id" @click="goDetail(m.id)">
          <MovieCard :movie="m" :cardWidth="200" :posterHeight="260" />
          <div class="score-row" :aria-label="`我的评分 ${fmt(m.score)} / 5`">
            <div class="stars">
              <span v-for="n in 5" :key="n" class="star">
                <span class="star-bg">★</span>
                <span class="star-fill" :style="{ width: starFillPercent(m.score, n) }">★</span>
              </span>
            </div>
            <div class="score">{{ fmt(m.score) }}</div>
          </div>
        </div>
      </div>
      <div v-else class="empty">你还没有评分任何影片，去看看热门电影吧～</div>

      <!-- 分页器 -->
      <div class="pager" v-if="totalPages > 1">
        <button class="page-btn" :disabled="page === 1" @click="toPrev">上一页</button>
        <span class="page-info">第 {{ page }} / {{ totalPages }} 页</span>
        <button class="page-btn" :disabled="page === totalPages" @click="toNext">下一页</button>
      </div>
    </div>
  </div>
 </template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getUserRatings } from '@/services/api'
import BrandHeader from '@/components/BrandHeader.vue'
import MovieCard from '@/components/MovieCard.vue'

const router = useRouter()
const items = ref([])
const PER_PAGE = 28
const page = ref(1)
const totalPages = computed(() => Math.max(1, Math.ceil(items.value.length / PER_PAGE)))
const pageItems = computed(() => {
  const start = (page.value - 1) * PER_PAGE
  return items.value.slice(start, start + PER_PAGE)
})

function normalizeItem(r) {
  // 兼容后端返回的字段并映射到 MovieCard 需要的结构
  return {
    id: r.movieId ?? r.id ?? r.movie_id,
    movieId: r.movieId ?? r.id ?? r.movie_id,
    title: r.title || '未知标题',
    year: r.year || '',
    genres: r.genres || '',
    poster: r.poster || '',
    score: Number(r.score) || 0
  }
}

function fmt(v) { const n = Number(v) || 0; return n.toFixed(1) }
function starFillPercent(score, n) {
  const s = Math.max(0, Math.min(5, Number(score) || 0))
  const fill = Math.max(0, Math.min(1, s - (n - 1)))
  return `${Math.round(fill * 100)}%`
}

function goDetail(id) { if (id) router.push({ name: 'movie', params: { id } }) }
function goBack() { if (window.history.length > 1) router.back(); else router.push('/recommend') }
function toPrev() { if (page.value > 1) page.value-- }
function toNext() { if (page.value < totalPages.value) page.value++ }

onMounted(async () => {
  try {
    const token = localStorage.getItem('token')
    // 拉取较多条目，前端分页（如需可将 1000 调小/调大）
    const res = await getUserRatings(token, 1000)
    const list = Array.isArray(res.data) ? res.data : []
    items.value = list.map(normalizeItem)
    page.value = 1
  } catch (e) {
    console.error('获取我的评分失败', e)
    items.value = []
  }
})
</script>

<style scoped>
.page { min-height: 100vh; background: #0f0f0f; color: #fff; }
.container { padding: 16px; }
.head { display:flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.back-btn {
  background: #fff; color: #000; border: 1px solid #e5e5e5; border-radius: 10px; padding: 8px 14px;
  font-size: 16px; font-weight: 700; cursor: pointer; transition: background .15s ease, transform .1s ease;
}
.back-btn:hover { background: #f2f2f2; transform: translateY(-1px); }
.back-btn:focus-visible { outline: 2px solid #000; outline-offset: 2px; }
.title { margin: 0; font-size: 22px; font-weight: 800; }
.sub { color:#bdbdbd; font-size: 13px; }
.grid { display: grid; grid-template-columns: repeat(7, 200px); gap: 28px; justify-content: start; }
.cell { cursor: pointer; }
.score-row { display:flex; align-items: center; justify-content: space-between; padding: 8px 6px 0; }
.stars { display: inline-flex; gap: 3px; font-size: 14px; line-height: 1; }
.star { position: relative; width: 14px; height: 14px; display: inline-block; }
.star-bg, .star-fill { position: absolute; inset: 0; font-size: 14px; line-height: 14px; }
.star-bg { color: #555; }
.star-fill { color: #ffb300; overflow: hidden; white-space: nowrap; width: 0; }
.score { color:#ddd; font-weight: 600; font-size: 14px; }
.empty { color:#9aa0a6; text-align: center; padding: 40px 0; }

.pager {
  display:flex; align-items:center; gap: 12px; justify-content: center; margin-top: 18px;
}
.page-btn {
  background:#fff; color:#000; border: 1px solid #e5e5e5; border-radius: 8px; padding: 6px 12px; cursor: pointer;
}
.page-btn:disabled { opacity: .5; cursor: not-allowed; }
.page-info { color:#ddd; font-size: 14px; }

@media (max-width: 1400px) { .grid { grid-template-columns: repeat(6, 200px); } }
@media (max-width: 1200px) { .grid { grid-template-columns: repeat(5, 200px); } }
@media (max-width: 1000px) { .grid { grid-template-columns: repeat(4, 200px); } }
@media (max-width: 820px)  { .grid { grid-template-columns: repeat(3, 200px); } }
@media (max-width: 620px)  { .grid { grid-template-columns: repeat(2, 200px); } }
</style>